#ifndef TCPSERVER_H
#define TCPSERVER_H

#include "datacollect.h"
#include "faultdiagnosis.h"
#include <QTcpServer>
#include <QTcpSocket>
#include <QUdpSocket>
#include <QNetworkDatagram>
#include <QNetworkInterface>
#include <QDebug>
#include <QFile>
#include <QFileInfo>
#include <QSettings>
#include <QByteArray>
#include <QTimer>
#include <QThread>

#define TCP_SERVER_PORT 44444
#define UDP_SERVER_PORT 12345
#define UDP_CLIENT_PORT 54321
#define READ_BUFFER 64*1024
#define WRITE_PAYLOADSIZE 64*1024 // 每次发送块的大小n*1024B=nKB

enum _DataType
{
    TYPE_CMD=1, TYPE_DATA=2, TYPE_FILE=3, TYPE_INFO=4
};

class udpServer : public QUdpSocket
{
    Q_OBJECT
public:
    udpServer(QObject *parent = nullptr);
    virtual ~udpServer();

public slots:
    void readPendingDatagrams();
    void sendPendingDatagrams();
    void sendDatagrams();
    void readIpAndHostName();
    void errorOccur();

private:
    QString var_IpAddress;
    QString var_HostName;
    qint64 var_receivedCMD;
};

class tcpServer : public QObject
{
    Q_OBJECT
public:
    tcpServer();
    ~tcpServer();
    bool start();

public slots:
    void sendDataFiles();
    void sendDiagnosisResult(QString result);
    void sendInformation(QString result);
    void accpetConnection();
    void errorOccur();
    void readySend(qint64 bytesWritten);
    void readyReceive();

signals:
    void dataCollectionSignal(const qint64 cmd);
    void faultDiagnosisSignal();

private:
    QTcpServer *var_server;
    QTcpSocket *var_socket;
    QFile var_file;
    udpServer *var_udpServer;
    QThread *var_udpThread;
    DataCollect *var_dataCollect;
    QThread *var_dataCollectThread;
    FaultDiagnosis *var_faultDiagnosis;
    QThread *var_faultDiagnosisThread;
    // 接收
    qint8 var_dataType;
    qint64 var_bytesHaveRecieve;
    qint64 var_totalBytesShouldRecieve;
    qint64 var_receivedCMD;
    // 发送
    QByteArray var_dataBlock;
    QByteArray var_fileBlock;
    qint64 var_fileBytesHaveSent;
    qint64 var_fileTotalBytes;
    qint64 var_dataTotalBytes;
    bool var_isSendFilesComplete;
};

#endif // TCPSERVER_H
